import mapboxgl from "mapbox-gl";
import * as THREE from "three";
import {OrbitControls} from "three/examples/jsm/controls/OrbitControls";


// export const noFlyClick = (map, count) => {
//     let draw = new MapboxDraw({
//         displayControlsDefault: false, // 根据需要显示或隐藏控件
//     });
//     map.addControl(draw);
//     map.on('click', function (e) {
//         // 添加一个3D圆柱体
//         const cylinder = {
//             "type": "Feature",
//             "geometry": {
//                 "type": "Polygon",
//                 "coordinates": [
//                     [ // 外环经纬度坐标数组
//
//                     ]
//                 ]
//             },
//             "properties": {
//                 "name": "Cylinder" // 可以添加其他属性用于后续处理或显示信息
//             }
//         };
//         draw.add(cylinder); // 使用Draw控件添加到地图上
//     })
//
//
//
// }

const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
const camera = new THREE.PerspectiveCamera(75,  window.innerWidth/window.innerHeight, 0.1, 1000);

export const noFlyClick = (map, count) => {

    clickEvent(map, count);

    moveEvent(map);

    rightClickEvent(map);

}

function clickEvent(map, count) {
    map.on('click', function (e) {
        // 当前圆柱体地理位置，及展示在three.js所需参数
        // 需要放在哪个位置
        if (e.originalEvent.button === 0) { // 确保是鼠标左键点击
            const modelOrigin = [e.lngLat.lng, e.lngLat.lat]
            var modelAltitude = 0;
            var modelRotate = [Math.PI / 2, 0, 0];
            var modelScale = 5.41843220338983e-8;
            let modelTransform = {
                translateX: mapboxgl.MercatorCoordinate.fromLngLat(modelOrigin, modelAltitude).x,
                translateY: mapboxgl.MercatorCoordinate.fromLngLat(modelOrigin, modelAltitude).y,
                translateZ: mapboxgl.MercatorCoordinate.fromLngLat(modelOrigin, modelAltitude).z,
                rotateX: modelRotate[0],
                rotateY: modelRotate[1],
                rotateZ: modelRotate[2],
                scale: modelScale
            };
            var customLayer = {
                id: '3dmodel' + count,
                type: 'custom',
                renderingMode: '3d',
                onAdd: function (map, gl) {
                    // var height = 20; // 圆柱体高度，可以根据需要调整
                    // var radiusInMeters = 5000; // 半径5km
                    // 添加圆柱体形状
                    var cylinder = new THREE.CylinderGeometry(50, 50, 200, 32);
                    // 添加材质
                    var materials = new THREE.MeshBasicMaterial({
                        color: '#fdff6e',
                        side: THREE.DoubleSide,
                        opacity: 0.5,
                        transparent: true
                    });
                    cylinder.userData = {layerId: '3dmodel' + count}
                    var cylinderMesh = new THREE.Mesh(cylinder, materials);
                    // 创建光线
                    this.directionalLight = new THREE.DirectionalLight(0xffffff);
                    this.directionalLight.position.set(0, 50, 100).normalize();
                    this.scene = new THREE.Scene();
                    this.scene.add(this.directionalLight);
                    this.camera = new THREE.PerspectiveCamera(
                        75,
                        window.innerWidth/window.innerHeight,
                        0.1,
                        1000);

                    // gltf加载器
                    this.scene.add(cylinderMesh);
                    // s获取Mapbox GL JS map canvas到three.js中
                    this.map = map;
                    this.renderer = new THREE.WebGLRenderer({
                        canvas: map.getCanvas(),
                        context: gl
                    });
                    this.renderer.autoClear = false;

                },
                render: function (gl, matrix) {
                    // 矩阵坐标转换
                    var rotationX = new THREE.Matrix4().makeRotationAxis(new THREE.Vector3(1, 0, 0), modelTransform.rotateX);
                    var rotationY = new THREE.Matrix4().makeRotationAxis(new THREE.Vector3(0, 1, 0), modelTransform.rotateY);
                    var rotationZ = new THREE.Matrix4().makeRotationAxis(new THREE.Vector3(0, 0, 1), modelTransform.rotateZ);

                    var m = new THREE.Matrix4().fromArray(matrix);
                    var l = new THREE.Matrix4().makeTranslation(modelTransform.translateX, modelTransform.translateY, modelTransform.translateZ)
                        .scale(new THREE.Vector3(modelTransform.scale, -modelTransform.scale, modelTransform.scale))
                        .multiply(rotationX)
                        .multiply(rotationY)
                        .multiply(rotationZ);

                    this.camera.projectionMatrix.elements = matrix;
                    this.camera.projectionMatrix = m.multiply(l);
                    this.renderer.state.reset();
                    this.renderer.render(this.scene, this.camera);
                    //渲染
                    this.map.triggerRepaint();
                }
            };
            map.addLayer(customLayer);
            count++;
        }
    });
}

// 单独列出 复用
function moveEvent(map) {
    map.on('mousemove', function (e) {
        // 坐标转换
        mouse.x = (e.originalEvent.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(e.originalEvent.clientY / window.innerHeight) * 2 + 1;
        // 同步Three.js相机参数（关键步骤）
        const projectionMatrix = map.getFreeCameraOptions().projectionMatrix;
        camera.projectionMatrix.fromArray(projectionMatrix);
        raycaster.setFromCamera(mouse, camera);
        const intersects = raycaster.intersectObjects(this.scene.children);

        if (intersects.length > 0) {
            for (let obj of intersects) {
                const layerId = obj.object.userData.layerId;
                if (layerId && layerId.slice(0,7) === '3dmodel') {
                    console.log('Hovered Layer ID:', layerId); // 输出当前图层ID
                }
            }
        }
    });
}

// 右键删除 优化
function rightClickEvent(map, count) {
    // 使用contextmenu事件监听右键点击
    map.on('contextmenu', function (e) {
        if (e.originalEvent.button === 2 && count > 0) { // 确保是鼠标右键点击
            // 将点击位置的经纬度坐标转换为屏幕坐标
            var coordinates = e.lngLat; // 获取点击位置的经纬度
            var pixel = map.project(coordinates); // 将经纬度转换为屏幕像素坐标
            var threeVector = new THREE.Vector2(pixel.x, map.getCanvas().height - pixel.y); // 转换为Three.js的Vector2

            // var raycaster = new THREE.Raycaster(); // 创建光线投射器对象
            // 获取与圆柱体相交的物体数组
            var removeLayer = false;
            for (let i=0; i<count; i++) {
                // 查询点击位置对应的图层特征
                var layerId = '3dmodel' + i;
                if (map.getLayer(layerId)) {
                    raycaster.setFromCamera(threeVector, map.getLayer(layerId).implementation.camera); // 通过鼠标点击位置和相机位置设置光线投射器对象的方向和起点
                    var intersects = raycaster.intersectObject(map.getLayer(layerId).implementation.scene.children[1]);
                    if (intersects && intersects.length > 0) {
                        debugger;
                        const intersectedObject = intersects[0].object;
                        console.log(intersectedObject);
                        map.removeLayer(layerId);
                        removeLayer = true;
                        return;
                    }
                }

            }
        }
    });
}

